package com.groot.medical.servlet;

import java.io.IOException;

import java.sql.PseudoColumnUsage;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.internal.runners.statements.Fail;

import com.google.gson.Gson;
import com.groot.common.controller.BaseServletController;
import com.groot.common.util.SimpleDateUtil;
import com.groot.medical.entity.AdministrativeArea;
import com.groot.medical.entity.FamilyArchives;
import com.groot.medical.entity.Menu;
import com.groot.medical.entity.PageBean;
import com.groot.medical.entity.PersonalFiles;
import com.groot.medical.entity.Role;
import com.groot.medical.entity.SysUser;
import com.groot.medical.service.AdministrativeAreaService;
import com.groot.medical.service.AdministrativeAreaServiceImpl;
import com.groot.medical.service.FamilyArchivesService;
import com.groot.medical.service.FamilyArchivesServiceImpl;
import com.groot.medical.service.PayService;
import com.groot.medical.service.PayServiceImpl;
import com.groot.medical.service.PersonalFileService;
import com.groot.medical.service.PersonalFileServiceImpl;



@WebServlet("/sys/family.do")
public class FamilyArchivesController extends BaseServletController{
	private FamilyArchivesService familyArchivesService = new FamilyArchivesServiceImpl();
	private AdministrativeAreaService areaService = new AdministrativeAreaServiceImpl();
	private PersonalFileService personService = new PersonalFileServiceImpl();
	private PayService payService = new PayServiceImpl();
	private static final long serialVersionUID = 1L;
	
	
	
	private static Logger LOGGER = Logger.getLogger(LoginController.class);
	
	public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LOGGER.info("this is @WebServlet(\"/index.do\").execute()");
		return null;
	}
	/**
	 * 分页查询家庭档案信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String findFamilyByPage (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String tgId = request.getParameter("tgId");
		int pageNum = Integer.valueOf(request.getParameter("pageNum"));
		List<Menu> menus=(List<Menu>) request.getSession().getAttribute("menuList");
		List<Menu> result = new ArrayList<Menu>();
		/*根据页面传过来的id与该用户所有权限的上一级id比较
		 * 若该权限的上一级传过来的id相同则存入新集合
		 */
		for(Menu menu: menus){
			if(menu.getMenuPid().equals(tgId)){
				result.add(menu);
			}
		}
		Gson gson = new Gson();
		request.setAttribute("resultMenus", gson.toJson(result));
		request.setAttribute("tgId", tgId);
		int pageSize = 5;
		PageBean areaPage = familyArchivesService.findByPage(pageNum, pageSize);
		System.out.println("areaPage:"+areaPage);
		request.setAttribute("areaPage", areaPage);
		return "/WEB-INF/page/family/family_list.jsp";
	}
	/**
	 * 打开添加参合家庭档案信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String openAddFamily(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("tgId",request.getParameter("tgId"));
		//查询所有县级行政区域信息
		List<AdministrativeArea> contryAreas=areaService.findContryAreaInfo();
		request.setAttribute("contryAreas", contryAreas);
		return "/WEB-INF/page/family/family_add.jsp";
	}
	/**
	 * 添加家庭档案信息和户主信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String addFamilyAndHolder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String tgId = request.getParameter("tgId");
		
		String areaContry = request.getParameter("areaContry");
		String areaTown = request.getParameter("areaTown");
		String areaVillage = request.getParameter("areaVillage");
		String groupArea = request.getParameter("groupArea");
		String familyProperty = request.getParameter("familyProperty");
		//户主姓名
		String familyHolder = request.getParameter("familyHolder");
		String familyAddress = request.getParameter("familyAddress");
		SysUser user=(SysUser) request.getSession().getAttribute("sysUser");
		
		//户主信息全部
		String familyInCode = request.getParameter("familyInCode");
		String holderRelation = request.getParameter("holderRelation");
		String idcardNumber = request.getParameter("idcardNumber");
		String Sex = request.getParameter("Sex");
		String Birthday = request.getParameter("Birthday");
		String Nation = request.getParameter("Nation");
		String Health = request.getParameter("Health");
		String cultrueDegree = request.getParameter("cultrueDegree");
		String personProperty = request.getParameter("personProperty");
		String isContryside = request.getParameter("isContryside");
		String isMarry = request.getParameter("isMarry");
		String workAddress = request.getParameter("workAddress");
		String phoneNumber = request.getParameter("phoneNumber");
		int personcounts=1;
		//获取当前时间
		
		FamilyArchives family = new FamilyArchives();
		family.setContryCode(areaContry);
		family.setTownCode(areaTown);
		family.setVillageCode(areaVillage);
		family.setGroupCode(groupArea);
		Date now = new Date();
		SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
		String nowTime = time.format(now);
		Date nowtime = null;
		try {
			nowtime = time.parse(nowTime);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Date startdate = null;
		try {
			startdate = time.parse(Birthday);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//判断是否农业人口
		if(Integer.parseInt(isContryside)==1){
			family.setAgriculturePersonCounts(1);
		}else{
			family.setAgriculturePersonCounts(0);
		}
		//封装进家庭档案实体类
		family.setFamilyProperty(familyProperty);
		family.setFamilyHolder(familyHolder);
		family.setFamilyPersonCounts(personcounts);
		family.setFamilyAddress(familyAddress);
		family.setCreateRchivesTime(nowtime);
		family.setRegistrarer(user.getUsername());

		//封装进户主信息实体（参合农民档案）
		PersonalFiles person = new PersonalFiles();
		person.setName(familyHolder);
		person.setFamilyInCode(familyInCode);
		person.setHolderRelation(holderRelation);
		person.setIdcardNumber(idcardNumber);
		person.setSex(Sex);
		person.setBirthday(startdate);
		person.setNation(Nation);
		person.setHealth(Health);
		person.setCultrueDegree(cultrueDegree);
		person.setPersonProperty(personProperty);
		person.setIsContryside(isContryside);
		person.setIsMarry(isMarry);
		person.setWorkAddress(workAddress);
		person.setPhoneNumber(phoneNumber);
		
		
		//添加家庭档案信息
		int i = familyArchivesService.addFamilyInfo(family);
		if(i!=0){
			
			personService.addHolderPersonInfo(person,groupArea);
			request.setAttribute("tgId", tgId);
			
			    
			return findFamilyByPage(request,response);
		}
		 return "/WEB-INF/page/family/family_add.jsp";
		
	}
	/**
	 * 打开修改家庭档案页面
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String openEditFamily(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("tgId",request.getParameter("tgId"));
		String familyCode = request.getParameter("id");
		//查询家庭信息档案显示页面
		FamilyArchives family = familyArchivesService.findFamilyInfoByFamilyCode(familyCode);
		//根据地区代码查询对应地区名称
		List<String> areaNames = new ArrayList<String>();
		areaNames = familyArchivesService.findAreaName(family);
		String contryName=areaNames.get(0);
		String townName=areaNames.get(1);
		String valligeName=areaNames.get(2);
		String groupName=areaNames.get(3);
		for (int i = 0; i < areaNames.size(); i++) {

			String str = areaNames.get(i);

			System.out.println(str);
			}
		
		//查询所有县级行政区域信息
		List<AdministrativeArea> contryAreas=areaService.findContryAreaInfo();
		
		request.setAttribute("family", family);
		request.setAttribute("contryName", contryName);
		request.setAttribute("townName", townName);
		request.setAttribute("valligeName", valligeName);
		request.setAttribute("groupName", groupName);
		request.setAttribute("contryAreas", contryAreas);
		return "/WEB-INF/page/family/family_edit.jsp";
		
	}

	/*
	 * 根据家庭编号查询家庭成员列表
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String findFamilyAllPerson(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			String familyCode = request.getParameter("familyCode");
			//根据家庭编号查询家庭成员列表
			List<PersonalFiles> persons = familyArchivesService.findFamilyAllPersonByFamilyCode(familyCode);
			request.setAttribute("persons", persons);
			return "/WEB-INF/page/family/family_person.jsp";
	}
	/**
	 * 修改家庭档案信息
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public String editFamilyAndHolder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String tgId = request.getParameter("tgId");
		
		String areaContry = request.getParameter("areaContry");
		String areaTown = request.getParameter("areaTown");
		String areaVillage = request.getParameter("areaVillage");
		String groupArea = request.getParameter("groupArea");
		String familyProperty = request.getParameter("familyProperty");
		String familyHolder = request.getParameter("familyHolder");
		String familyPersonCounts = request.getParameter("familyPersonCounts");
		String agriculturePersonCounts = request.getParameter("agriculturePersonCounts");
		String createRchivesTime = request.getParameter("createRchivesTime");
		String Registrarer = request.getParameter("Registrarer");
		String familyAddress = request.getParameter("familyAddress");
		String familyCode = request.getParameter("familyCode");
		
		FamilyArchives family = new FamilyArchives();
		family.setContryCode(areaContry);
		family.setTownCode(areaTown);
		family.setVillageCode(areaVillage);
		family.setGroupCode(groupArea);
		family.setFamilyProperty(familyProperty);
		family.setFamilyHolder(familyHolder);
		family.setFamilyPersonCounts(Integer.valueOf(familyPersonCounts));
		family.setAgriculturePersonCounts(Integer.valueOf(agriculturePersonCounts));
		family.setCreateRchivesTime(SimpleDateUtil.StringToDate(createRchivesTime));
		family.setRegistrarer(Registrarer);
		family.setFamilyAddress(familyAddress);
		family.setFamilyCode(familyCode);
		//执行修改
		familyArchivesService.ediFamilyInfo(family);
		request.setAttribute("tgId", tgId);
		return findFamilyByPage(request,response);
	}
	/**
	 * 删除家庭档案
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void deleteFamily(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String familyCode = request.getParameter("familycode");
		System.out.println(familyCode);
		String resultString = "false";
		//查询是否存在业务记录
		int counts = payService.findIsExsitService(familyCode);
		if(counts>0){
			resultString = "false";
			response.setContentType("text/html");
	        ServletOutputStream outputStream = response.getOutputStream();
	        outputStream.write(resultString.getBytes());
	        outputStream.close();
		}else{
			//删除家庭档案
			int i = familyArchivesService.deleteFamily(familyCode);
			System.out.println(i);
			resultString = "true";
			response.setContentType("text/html");
	        ServletOutputStream outputStream = response.getOutputStream();
	        outputStream.write(resultString.getBytes());
	        outputStream.close();
		}
		
	}
}
